import { setGlobal } from '@swda/utils'

//=============================================================================
// Sprite_ATB
// ATB条上的角色图标
//=============================================================================
function Sprite_ATB() {
    this.initialize.apply(this, arguments);
}

Sprite_ATB.prototype = Object.create(Sprite_Base.prototype);
Sprite_ATB.prototype.constructor = Sprite_ATB;


Sprite_ATB.prototype.initialize = function(battler, startY, endY) {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
    this._startY = startY;
    this._endY = endY;
    this.setBattler(battler);
};

Sprite_ATB.prototype.initMembers = function() {
    this.anchor.x = 1;
    this.anchor.y = 0.5;
    this._battler = null;
    this._class = 0;
    this._actionEffectCount = 0;
    this._requestRefresh = false;
    this._currentATBSpeed = 0;
    this._currentATBCharge = 0;
    this._atbRate = 0;
    this._headSprite = new Sprite();
    this._headSprite.anchor.x = 0.5;
    this._headSprite.anchor.y = 0.5;
    this.addChild(this._headSprite);
};


Sprite_ATB.prototype.setBattler = function(battler) {
    this._battler = battler;
    this.setBitmap();
};

Sprite_ATB.prototype.setBitmap = function() {
    if (!this.battler()) return;
    
    if (this.battler().isPet()){
        this.bitmap = ImageManager.loadBitmap('img/system/UI/', 'atbActor');
        this.setFrame(0, 0, 56, 37);
        this.anchor.x = 49.5/56;
        this._headSprite.bitmap = ImageManager.loadSystem('IconSet');
        this._headSprite.x = -33;

        this._class = this.battler()._classId;
        let battlerClassIcon = Window_Base.prototype.enemyClassIcon(this._class);
        //let battlerClassIcon = (this._class>=6 && this._class<=20) ? this._class - 6 + 145 : 144;
        let pw = Window_Base._iconWidth;
        let ph = Window_Base._iconHeight;
        let sx = battlerClassIcon % 16 * pw;
        let sy = Math.floor(battlerClassIcon / 16) * ph;
        this._headSprite.setFrame(sx, sy, pw, ph);

    } else if (this.battler().isActor()){
        const bitmapName = 'head' + this.battler().actorId() + ((this.battler().actorId()==1 && $gameSwitches.value(299)) ? "a" : "");
        this.bitmap = ImageManager.loadBitmap('img/system/UI/', 'atbActor');
        this.setFrame(0, 0, 56, 37);
        this.anchor.x = 49.5/56;
        this._headSprite.bitmap = ImageManager.loadBitmap('img/system/actors/', bitmapName);
        this._headSprite.x = -33;
        this._class = 0;

    } else if (this.battler().isEnemy()){
        this.bitmap = ImageManager.loadBitmap('img/system/UI/', 'atbEnemy');
        this.setFrame(0, 0, 56, 37);
        this.anchor.x = 6.5/56;
        this._headSprite.bitmap = ImageManager.loadSystem('IconSet');
        this._headSprite.x = 30;

        this._class = this.battler()._classId;
        let battlerClassIcon = Window_Base.prototype.enemyClassIcon(this._class);
        //let battlerClassIcon = (this._class>=6 && this._class<=20) ? this._class - 6 + 145 : 144;
        let pw = Window_Base._iconWidth;
        let ph = Window_Base._iconHeight;
        let sx = battlerClassIcon % 16 * pw;
        let sy = Math.floor(battlerClassIcon / 16) * ph;
        this._headSprite.setFrame(sx, sy, pw, ph);
    } 
    
};

Sprite_ATB.prototype.battler = function() {
    return this._battler;
};

//更新
Sprite_ATB.prototype.update = function() {
    if(BattleManager.isBattleEnd()||BattleManager.isEscaped()||$gameMessage.isBusy()||BattleManager._phase === 'start'){
        return;
    }
    Sprite_Base.prototype.update.call(this);
    if (this.battler()) {
        this.updateSelectionEffect();
        this.updateActionEffect();
        this.updateChargingEffect();
        this.updateAtbRate();
        this.updatePosition();
    } else {
        this.bitmap = null;
    }
};


// 是否可见
Sprite_ATB.prototype.updateVisibility = function() {
    Sprite_Base.prototype.updateVisibility.call(this);
    if (!this.battler() || this.battler().isDead() || this.battler().isHidden()) {
        this.visible = false;
    }else if(this.battler().isEnemy()){
        this.visible = !(this.battler().isStranger() && !this.battler().atbCanMove());
    }
};

// 选择时闪烁
Sprite_ATB.prototype.updateSelectionEffect = function() {
    const battler = this.battler();
    if (this.isBattlerSelected()) {
        if(!battler.atbCanMove() && !battler.isStateAffected(18) )
            this._headSprite.setColorTone([100, 75, 20, 255]);
        else
            this._headSprite.setColorTone([100, 75, 20, 0]);
    } else {
        if(!battler.atbCanMove() && !battler.isStateAffected(18) )
            this._headSprite.setColorTone([0, 0, 0, 255]);
        else
            this._headSprite.setColorTone([0, 0, 0, 0]);
    }
};
// 角色被选择的判定
Sprite_ATB.prototype.isBattlerSelected = function() {
    return this.battler()._selected ||
     (((BattleManager._phase === 'actionList') || 
       (BattleManager._phase === 'actionTargetList') || 
       (BattleManager._phase === 'action') || 
       (BattleManager._phase === 'phaseChange')) &&
       BattleManager._targets.includes(this.battler()));
}
//ATB最快
Sprite_ATB.prototype.isBattlerATBFastest = function() {
    return BattleManager.isBattlerATBFastest(this.battler())
}
//ATB集满
Sprite_ATB.prototype.isBattlerATBReady = function() {
    return BattleManager.isBattlerATBReady(this.battler())
}

// 行动时
Sprite_ATB.prototype.updateActionEffect = function() {
    if (this.needUpdateActionEffect()) {
        this._actionEffectCount++;
        if (this._actionEffectCount % 30 < 15) {
            this.setFrame(0, 37, 56, 74);
        } else {
            this.setFrame(0, 0, 56, 37);
        }
    } else if (this._actionEffectCount > 0) {
        this._actionEffectCount = 0;
        this.setFrame(0, 0, 56, 37);
    }

};

Sprite_ATB.prototype.needUpdateActionEffect = function() {
    // charging问题（同时atb满或同时charging，详见AtbFix.js）解决后，不必再设置复杂条件，只需取fastest即可。
    return this.isBattlerATBFastest() || this.battler().isATBCharging()

    //（注：护驾会被判定isActor）
    //敌人+护驾
    /*
    if(this.battler().isActor() && !this.battler().isPet()){
        return  this.isBattlerATBFastest() || this.battler().isATBCharging()
        //this.battler().atbRate()>=1 &&
        //!(this.battler().isATBCharging() &&
        //this.battler().atbChargeRate()<1)
    }else{
        return this.isBattlerATBFastest() || this.battler().isATBCharging()
    }*/

}
// Charging时
Sprite_ATB.prototype.updateChargingEffect = function() {
    if(this.battler().atbChargeDenom() <= 1)
        return;// 如果无吟唱，则不更新atb背景颜色变化
    if (this.battler().isATBCharging() && this.battler().atbChargeRate()<1){
        this.setColorTone([100, 0, 0, 0]);
    }else{
        this.setColorTone([0, 0, 0, 0]);
    }

};

// 行动值有变化时更新(Position)
Sprite_ATB.prototype.updateAtbRate = function() {
    if (!this.battler()) return;
    
    if (this._currentATBSpeed !== this.battler().atbSpeed()) {
        let difference  = this._currentATBSpeed - this.battler().atbSpeed();
        if (this.curAtbRate()>=1 && !this.isBattlerSelected()){//条件后者防止atb满的敌人被攻击击退时atb跳变而非缓动
            this._currentATBSpeed = this.battler().atbSpeed();
        } else if (difference <= 0){
            this._currentATBSpeed = this.battler().atbSpeed();
        }else{
            //差值逐渐变小，速度逐渐变慢，慢到一定程度时匀速。（缓动）
            if (difference >0.1)
                this._currentATBSpeed -= difference / 8;
            else
                this._currentATBSpeed -= 0.0125;
        }
        this._requestRefresh = true;
    }
    // 仅在charging时更新atbChange的ATB位置
    if (this.battler().isATBCharging() && this.battler().atbChargeRate()<1){
        if (this._currentATBSpeed !== this.battler().atbCharge()) {
            this._currentATBSpeed = this.battler().atbCharge();
            this._currentATBCharge = true;
        }
    }
};


// ATB条当前显示的比率
Sprite_ATB.prototype.curAtbRate = function() {
    var rate = 0;
    if (this.battler().isATBCharging()){
        // 如果无吟唱，则rate始终为1，以防极端情况闪到rate=0的位置。
        if(this.battler().atbChargeDenom() <= 1)
            rate = 1;
        else
            rate = this._currentATBSpeed / this.battler().atbChargeDenom();
    }else{
        rate = this._currentATBSpeed / BattleManager.atbTarget();
    }
    return rate.clamp(0, 1);
};

// ATB标签缓动
Sprite_ATB.prototype.updatePosition = function() {
    if (this.isRequestRefresh()){
        this.y = this.atbY(this.curAtbRate());
        if (this._currentATBSpeed == this.battler().atbSpeed()) {
            this._requestRefresh = false;
        }
    }
};
// 计算atb轴y坐标
Sprite_ATB.prototype.atbY= function(atbRate) {
    return this._startY - atbRate * (this._startY - this._endY);
};

Sprite_ATB.prototype.isRequestRefresh = function() {
    return this._requestRefresh;
};



setGlobal('Sprite_ATB', Sprite_ATB)